package com.zxk.util;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

/**
 * 键盘操作工具类
 *
 * @author: 舟小亢
 * @date: 2023-08-13 11:22
 */
public class KeyUtil {

    /**
     * 双组合键按下并弹起（无效方法）
     *
     * @param keyValue1 按键1
     * @param keyValue2 按键2
     * @return
     */
    public static boolean kMultiClick(WinDef.HWND hwnd, long keyValue1, long keyValue2) {
        // 发送点击命令
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYDOWN, new WinDef.WPARAM(keyValue1), new WinDef.LPARAM());
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYDOWN, new WinDef.WPARAM(keyValue2), new WinDef.LPARAM());
        // 发送弹起命令
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYUP, new WinDef.WPARAM(keyValue2), new WinDef.LPARAM());
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYUP, new WinDef.WPARAM(keyValue1), new WinDef.LPARAM());
        return true;
    }

    /**
     * 键盘按下并弹起
     *
     * @param hwnd
     * @param keyValue
     * @return
     */
    public static boolean kClick(WinDef.HWND hwnd, long keyValue) throws Exception {
        kClickSync(hwnd, keyValue);
        // 等待程序响应
        ThreadUtil.sleep1();
        return true;
    }

    private static synchronized void kClickSync(WinDef.HWND hwnd, long keyValue) throws Exception {
        // 激活句柄
        User32.INSTANCE.SetForegroundWindow(hwnd);
        // 发送点击命令 todo 确认PostMessage和该方法的区别
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYDOWN, new WinDef.WPARAM(keyValue), new WinDef.LPARAM());
        ThreadUtil.sleep(100);
        // 发送弹起命令
        User32.INSTANCE.SendMessage(hwnd, User32.WM_KEYUP, new WinDef.WPARAM(keyValue), new WinDef.LPARAM());
    }

}
